#!python
# 
# SConscript for python bindings with dso

# Import everything under the sun
import SCons.Environment;     # Get the environment crap
import SCons;
import SConsAddons.Options;   # Get the modular options stuff
import SConsAddons.Options.Pyste
import SConsAddons.Util       # Get the utils
import sys, os, re,string

try:
   import wing.wingdbstub;       # stuff for debugging
except:
   print '[WRN] Unable to load wing debugging extensions'
import SConsAddons.AutoDist as AutoDist
import glob

pj = os.path.join;

Import('*')

rel_src_path = SConsAddons.Util.getRelativeSourcePath()

# ---- Pyste ----- #
pyenv = common_env.Copy()        # Get local env
pyste_options.updateEnv(pyenv, cacheDir=pj(rel_src_path,"_cache"))       # Add pyste builder, scanner, etc
opensg_options.updateEnv(pyenv, ['system'], optimize=True, useCppPath=True)

print "Opensg options: defines: ", opensg_options.found_defines

if(pyste_options.isAvailable()):
   print "Pyste available. Adding deps for code generation..."
   # --- OpenSG pyste files ---- #
   # Get a list of sources, then loop over the base name for each of them
   osg_pyste_src_files = [
      "TypeBase.pyste",
      "MemoryObject.pyste",
      "DataType.pyste",
      "FieldType.pyste",
      "FieldFactory.pyste",
      "FieldDescription.pyste",
      "FieldContainerType.pyste",
      "FieldContainerFactory.pyste",
      "FieldContainer.pyste",
      "Field.pyste",
      "ChangeList.pyste",
      "Volume.pyste",
      "VecStorage4.pyste",
      "VecStorage3.pyste",
      "Pnt.pyste",
      "Vec.pyste",
      "Matrix.pyste",
      "Quaternion.pyste",
      "Plane.pyste",
      "Color.pyste",
      "DynamicVolume.pyste",
      "RenderAction.pyste",
      "StatCollector.pyste",
      "BaseFunctions.pyste",
      "PtrFunctions.pyste",

      "SceneFileHandler.pyste",
      ]
   
   # Get gen files and then sort by their embedded keys  
   gen_files = glob.glob("gen_*.pyste")          # Get list of files
   sort_re = re.compile('GenSortOrder:(\d*)')
   # Build list of sort keys
   file_keys = [sort_re.search(file(f).read()).group(1) for f in gen_files]
   file_map = {}                         # Map key to file name
   for i in range(len(file_keys)):
      file_map[file_keys[i]] = gen_files[i]
   
   sorted_gen_files = []
   file_keys.sort()
   for k in file_keys:
      sorted_gen_files.append(file_map[k])   
   
   print "Sorted files: ", sorted_gen_files   
   osg_pyste_src_files += sorted_gen_files
   
   osg_pyste_src_files += [
      "SimpleGeometry.pyste",
      "SimpleSceneManager.pyste",
      "SimpleAttachments.pyste"
   ]

   for f in osg_pyste_src_files:
      tgt_name = 'gen/_%s.cpp'%(f[:-6],)
      src_name = f
      #print "t:%s  s:%s" % (tgt_name, src_name)
      pyenv.PysteMultiBuilder(tgt_name, src_name, PYSTE_MODULE='osg')
   pyenv.PysteMainBuilder('gen/_main.cpp', osg_pyste_src_files, PYSTE_MODULE='osg')
else:
   print "Pyste not available. Interface generation disabled."

